//ajax封装
function handleAjaxRequest(xhr, successCallback, errorCallback) {
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                try {
                    const response = JSON.parse(xhr.responseText);
                    if (response.success || response.url) {
                        successCallback(response);
                    } else {
                        errorCallback('操作失败：' + (response.error || '未知错误'));
                    }
                } catch (e) {
                    errorCallback('响应解析失败');
                }
            } else {
                errorCallback('请求失败，请重试');
            }
        }
    };
}

document.getElementById('avatar').addEventListener('change', function (e) {
    const file = e.target.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function (e) {
            document.getElementById('avatarPreview').src = e.target.result;
            document.getElementById('avatarPreviewContainer').style.display = 'block';
        }
        reader.readAsDataURL(file);
    }
});

// 上传头像功能
document.getElementById('uploadAvatarBtn').addEventListener('click', function () {
    const fileInput = document.getElementById('avatar');
    const file = fileInput.files[0];

    if (!file) {
        alert('请选择一个头像文件');
        return;
    }

    // 检查文件类型
    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
    if (!allowedTypes.includes(file.type)) {
        alert('只支持 JPG、PNG、GIF 格式的图片');
        return;
    }

    // 检查文件大小 (2MB)
    if (file.size > 2 * 1024 * 1024) {
        alert('文件大小不能超过 2MB');
        return;
    }

    const formData = new FormData();
    formData.append('avatar', file);

    const xhr = new XMLHttpRequest();
    xhr.open('POST', '/admin/uploadAvatar', true);  // 确保与Controller中的路径一致
    // 显示上传中提示
    const uploadBtn = document.getElementById('uploadAvatarBtn');
    const originalBtnText = uploadBtn.innerHTML;
    uploadBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>上传中...';
    uploadBtn.disabled = true;

    xhr.onload = function () {
        // 恢复按钮状态
        uploadBtn.innerHTML = originalBtnText;
        uploadBtn.disabled = false;

        if (xhr.status === 200) {
            try {
                const response = JSON.parse(xhr.responseText);
                if (response.success && response.url) {
                    // 更新页面上的头像显示
                    document.querySelectorAll('.user-avatar').forEach(img => {
                        // 只更新当前用户的头像
                        if (img.src.includes('avatar') || img.src.includes('defaultAvatar')) {
                            img.src = response.url;
                        }
                    });

                    // 关闭模态框
                    const modalElement = document.getElementById('updateAvatarModal');
                    const modal = bootstrap.Modal.getInstance(modalElement) || new bootstrap.Modal(modalElement);
                    modal.hide();

                    // 重置表单
                    document.getElementById('avatarForm').reset();
                    document.getElementById('avatarPreviewContainer').style.display = 'none';

                    alert('头像上传成功！');
                } else {
                    alert('头像上传失败：' + (response.error || '未知错误'));
                }
            } catch (e) {
                alert('响应解析失败');
            }
        } else {
            alert('上传失败，请重试');
        }
    };

    xhr.onerror = function () {
        // 恢复按钮状态
        uploadBtn.innerHTML = originalBtnText;
        uploadBtn.disabled = false;
        alert('网络错误，请重试');
    };

    xhr.send(formData);
});


//添加为管理员
function addAdmin(userId, buttonElement) {
    if (window.confirm('将该用户设置为管理员?')) {
        let xhr = new XMLHttpRequest();
        xhr.open("POST", "/admin/users/promote?userId=" + userId, true);
        xhr.setRequestHeader("Content-Type", "application/json")
        handleAjaxRequest(xhr,
            response => {
                // 局部更新页面，而不是刷新整个页面
                // 1. 更新角色显示为"管理员"
                const row = buttonElement.closest('tr');
                const roleCell = row.cells[2];
                roleCell.innerHTML = '<span class="badge bg-warning">管理员</span>';
                // 2. 隐藏"设为管理员"按钮
                buttonElement.style.display = 'none';
                alert('设置成功!');
            }, error => {
                alert(error)
            });
        xhr.send()
    }
}

//删除用户
function delUser(userId, buttonElement) {
    if (window.confirm('确认删除该用户?')) {
        let xhr = new XMLHttpRequest();
        xhr.open("DELETE", "/admin/users/" + userId, true);
        handleAjaxRequest(xhr,
            response => {
                if (response.success) {
                    alert('删除成功!');
                    //隐藏当前行即可
                    const row = buttonElement.closest('tr');
                    row.style.display = 'none';
                } else {
                    alert('删除失败: ' + (response.error || '未知错误'));
                }
            }, error => {
                alert("您的权限不足~")
            });
        xhr.send()
    }
}

//管理员降为用户
function demoteAdmin(adminId, buttonElement) {
    if (window.confirm('确认降为普通用户？')) {
        let xhr = new XMLHttpRequest();
        xhr.open("PUT", "/admin/admins/demote/" + adminId, true);
        handleAjaxRequest(xhr,
            response => {
                // 1. 在管理员页面隐藏当前行
                const adminRow = buttonElement.closest('tr');
                adminRow.style.display = 'none';

                // 2. 更新用户管理页面的角色信息（如果存在）
                updateUserInfoInUserManagement(adminId, '普通用户');
            },
            error => alert('您的权限不足~')
        );
        xhr.send();
    }
}

// 辅助函数：更新用户管理页面中的用户信息
function updateUserInfoInUserManagement(userId, role) {
    // 查找用户管理页面中对应用户的行
    const userRows = document.querySelectorAll('#userManagementTable tbody tr');
    for (let row of userRows) {
        const userIdCell = row.querySelector('.user-id');
        if (userIdCell && userIdCell.dataset.userId === userId.toString()) {
            // 更新角色显示
            const roleCell = row.cells[2];
            roleCell.innerHTML = `<span class="badge bg-secondary">${role}</span>`;

            // 更新按钮状态
            const promoteBtn = row.querySelector('.promote-admin-btn');
            if (promoteBtn) {
                promoteBtn.style.display = 'inline-block';
            }

            const demoteBtn = row.querySelector('.demote-admin-btn');
            if (demoteBtn) {
                demoteBtn.style.display = 'none';
            }

            break;
        }
    }
}

//删除管理员
function delAdmin(userId, buttonElement) {
    if (window.confirm('确认删除该管理员?')) {
        let xhr = new XMLHttpRequest();
        xhr.open("DELETE", "admin/admins/" + userId, true);
        handleAjaxRequest(xhr,
            response => {
                alert('删除成功!');
                //隐藏当前行即可
                const row = buttonElement.closest('tr');
                row.style.display = 'none';
            }, error => {
                alert('您的权限不足~')
            });
        xhr.send()
    }
}

//编辑用户
function editUser(userId, buttonElement) {
    let userRow = buttonElement.closest('tr');
    let status = userRow.cells[4].textContent
    document.getElementById('editUserId').value = userId
    document.getElementById('editStatus').seleted = status
    let editModal = new bootstrap.Modal(document.getElementById('editUserModal'));
    editModal.show();
}

let editBtn = document.getElementById('saveUserBtn');
editBtn.addEventListener('click', function () {
    let data = {
        id: document.getElementById('editUserId').value,
        password: document.getElementById('editPassword').value,
        status: document.getElementById('editStatus').value
    }
    console.log(data)
    console.log(JSON.stringify(data))
    let xhr = new XMLHttpRequest();
    xhr.open("POST", "/admin/users", true);
    xhr.setRequestHeader("Content-Type", "application/json");
    handleAjaxRequest(xhr,
        response => {
            alert('编辑成功')
            const editModal = bootstrap.Modal.getInstance(document.getElementById('editUserModal'));
            if (editModal) {
                editModal.hide();
            }
        }, error => {
            alert(error)
        })
    xhr.send(JSON.stringify(data))
})

//删除资源
function delResource(resourceId, buttonElement) {
    if (window.confirm('确认删除该资源?')) {
        let xhr = new XMLHttpRequest();
        xhr.open("DELETE", "/admin/resources/" + resourceId, true);
        handleAjaxRequest(xhr,
            response => {
                alert('删除成功!');
                //隐藏当前行即可
                const row = buttonElement.closest('tr');
                row.style.display = 'none';
            }, error => {
                alert('您的权限不足~')
            });
        xhr.send()
    }
}

//删除作业
function delAssignment(assignmentId, buttonElement) {
    if (window.confirm('确认删除该资料?')) {
        let xhr = new XMLHttpRequest();
        xhr.open("DELETE", "/admin/assignments/" + assignmentId, true);
        handleAjaxRequest(xhr,
            response => {
                alert('删除成功!');
                //隐藏当前行即可
                const row = buttonElement.closest('tr');
                row.style.display = 'none';
            }, error => {
                alert('您的权限不足~')
            });
        xhr.send()
    }
}

//删除帖子
function delPost(postId, buttonElement) {
    if (window.confirm('确认删除该帖子?')) {
        let xhr = new XMLHttpRequest();
        xhr.open("DELETE", "/admin/posts/" + postId, true);
        handleAjaxRequest(xhr,
            response => {
                alert('删除成功!');
                //隐藏当前行即可
                const row = buttonElement.closest('tr');
                row.style.display = 'none';
            }, error => {
                alert('您的权限不足~')
            });
        xhr.send()
    }
}

//置顶帖子
function topPost(postId, isTop, buttonElement) {
    // 获取当前帖子的isTop状态
    // 计算新的状态（0表示未置顶，1表示已置顶）
    const newIsTop = isTop === 1 ? 0 : 1;

    const url = `/admin/posts/${postId}/top/${newIsTop}`;
    const method = 'POST';
    const xhr = new XMLHttpRequest();
    xhr.open(method, url, true);
    xhr.setRequestHeader('Content-Type', 'application/json');

    handleAjaxRequest(xhr,
        response => {
            if (response.success) {
                // 切换按钮文本
                const buttonText = buttonElement.querySelector('span');
                buttonText.textContent = newIsTop === 1 ? '取消置顶' : '置顶';

                // 切换按钮样式
                if (newIsTop === 1) {
                    buttonElement.classList.remove('btn-info');
                    buttonElement.classList.add('btn-warning');
                } else {
                    buttonElement.classList.remove('btn-warning');
                    buttonElement.classList.add('btn-info');
                }

                // 更新状态标签
                const row = buttonElement.closest('tr');
                const statusBadges = row.querySelectorAll('.status-badge');

                // 查找并更新置顶状态标签
                statusBadges.forEach(badge => {
                    if (badge.textContent.includes('置顶')) {
                        if (newIsTop === 1) {
                            badge.classList.remove('secondary');
                            badge.classList.add('warning');
                            badge.textContent = '已置顶';
                        } else {
                            badge.classList.remove('warning');
                            badge.classList.add('secondary');
                            badge.textContent = '未置顶';
                        }
                    }
                });

                // 同时更新传递给函数的isTop参数，以便下次点击时状态正确
                buttonElement.setAttribute('onclick',
                    'topPost(' + postId + ',' + newIsTop + ',this)');

                alert('操作成功！');
            } else {
                alert('操作失败：' + (response.error || '未知错误'));
            }
        },
        error => {
            alert('您的权限不足~');
        }
    );
    xhr.send();
}


//加精帖子
function enhancePost(postId, isElite, buttonElement) {
    // 计算新的状态（0表示普通，1表示精华）
    const newIsElite = isElite === 1 ? 0 : 1;

    let xhr = new XMLHttpRequest();
    xhr.open("POST", "/admin/posts/" + postId + "/highlight/" + newIsElite, true);
    handleAjaxRequest(xhr,
        response => {
            if (response.success) {
                // 切换按钮文本
                const buttonText = buttonElement.querySelector('span');
                buttonText.textContent = newIsElite === 1 ? '取消加精' : '加精';

                // 切换按钮样式
                if (newIsElite === 1) {
                    buttonElement.classList.remove('btn-success');
                    buttonElement.classList.add('btn-warning');
                } else {
                    buttonElement.classList.remove('btn-warning');
                    buttonElement.classList.add('btn-success');
                }

                // 更新状态标签
                const row = buttonElement.closest('tr');
                const statusBadges = row.querySelectorAll('.status-badge');

                // 查找并更新加精状态标签
                statusBadges.forEach(badge => {
                    if (badge.textContent.includes('精华') || badge.textContent.includes('普通')) {
                        if (newIsElite === 1) {
                            badge.classList.remove('secondary');
                            badge.classList.add('success');
                            badge.textContent = '精华';
                        } else {
                            badge.classList.remove('success');
                            badge.classList.add('secondary');
                            badge.textContent = '普通';
                        }
                    }
                });

                // 同时更新传递给函数的isElite参数，以便下次点击时状态正确
                buttonElement.setAttribute('onclick',
                    'enhancePost(' + postId + ',' + newIsElite + ',this)');

                alert('操作成功！');
            } else {
                alert('操作失败：' + (response.error || '未知错误'));
            }
        }, error => {
            alert('您的权限不足~')
        });
    xhr.send()
}
// 查看学习资源
function viewResource(id, element) {
    let xhr = new XMLHttpRequest()
    xhr.open("GET", "/admin/resources/" + id, true)
    handleAjaxRequest(xhr,
        response => {
            const resourceId = response.id;
            const resourceTitle = response.title;
            const resourceMajor = response.major;
            const resourceType = response.type;
            const resourceFileSize = response.fileSize;
            const resourceCreatedTime = response.createTime;
            const resourceStatus = response.status;
            const resourceDownloadCount = response.downloadCount;
            const resourceViewCount = response.viewCount;
            const resourceDescription = response.description;

            // 显示模态框
            const modal = new bootstrap.Modal(document.getElementById('viewResourceModal'));
            modal.show();

            // 填充数据
            document.getElementById('resourceId').value = resourceId;
            document.getElementById('resourceTitle').textContent = resourceTitle;
            document.getElementById('resourceMajor').textContent = resourceMajor;
            document.getElementById('resourceType').textContent = resourceType;
            document.getElementById('resourceFileType').textContent = resourceType;
            document.getElementById('resourceFileSize').textContent = resourceFileSize;
            document.getElementById('resourceCreatedTime').textContent = resourceCreatedTime;
            document.getElementById('resourceStatus').textContent = resourceStatus === 1 ? '正常' : '禁用';
            document.getElementById('resourceStatus').className = "form-control-plaintext text-success";
            document.getElementById('resourceDownloadCount').textContent = resourceDownloadCount;
            document.getElementById('resourceViewCount').textContent = resourceViewCount;
            document.getElementById('resourceDescription').textContent = resourceDescription;

            // 设置下载链接
            document.getElementById('downloadResourceBtn').href = "/resource/download/" + resourceId;

            // 设置状态切换按钮
            const toggleBtn = document.getElementById('toggleResourceStatusBtn');
            if (resourceStatus === 1) {
                toggleBtn.innerHTML = '<i class="fas fa-ban me-1"></i>禁用资源';
                toggleBtn.className = "btn btn-warning";
                toggleBtn.onclick = function() {
                    toggleResourceStatus(resourceId, 0);
                };
            } else {
                toggleBtn.innerHTML = '<i class="fas fa-save me-1"></i>启用资源';
                toggleBtn.className = "btn btn-success";
                toggleBtn.onclick = function() {
                    toggleResourceStatus(resourceId, 1);
                };
            }
        }, error => {
            alert('查看失败!')
        })
    xhr.send();

}
//切换资源状态
function toggleResourceStatus(resourceId, status) {
    if (window.confirm(status === 1 ? '确认启用该资源?' : '确认禁用该资源?')) {
        let xhr = new XMLHttpRequest();
        xhr.open("GET", "/resource/isAvailable/" + resourceId + "/" + status, true);
        handleAjaxRequest(xhr,
            response => {
                if (response.success) {
                    alert(status === 1 ? '资源已启用!' : '资源已禁用!');
                    // 关闭模态框
                    const modalElement = document.getElementById('viewResourceModal');
                    const modal = bootstrap.Modal.getInstance(modalElement);
                    if (modal) {
                        modal.hide();
                    }
                } else {
                    alert('操作失败: ' + (response.error || '未知错误'));
                }
            }, error => {
                alert('您的权限不足~');
            });
        xhr.send();
    }
}


// 查看作业
function viewAssignment(id, element) {
    let xhr = new XMLHttpRequest()
    xhr.open("GET", "/admin/assignments/" + id, true)
    handleAjaxRequest(xhr,
        response=>{
            const assignmentId = response.id;
            const assignmentTitle = response.title;
            const assignmentMajor = response.major;
            const assignmentStatus = response.status;
            const assignmentCreatedTime = response.createdTime;
            const assignmentDeadline = response.deadline;
            const assignmentDescription = response.description;

            // 显示模态框
            const modal = new bootstrap.Modal(document.getElementById('viewAssignmentModal'));
            modal.show();

            // 填充数据
            document.getElementById('assignmentId').value = assignmentId;
            document.getElementById('assignmentTitle').textContent = assignmentTitle;
            document.getElementById('assignmentMajor').textContent = assignmentMajor;
            document.getElementById('assignmentStatus').textContent = assignmentStatus === 1 ? '进行中' : '已结束';
            document.getElementById('assignmentStatus').className = "form-control-plaintext " + (assignmentStatus === 1 ? "text-success" : "text-danger");
            document.getElementById('assignmentCreatedTime').textContent = assignmentCreatedTime;
            document.getElementById('assignmentDeadline').textContent = assignmentDeadline;
            document.getElementById('assignmentDescription').textContent = assignmentDescription;

            // 获取作业提交列表
            getAssignmentSubmissions(assignmentId);
        },error=>{alert('查看失败!')})
    xhr.send();
}

// 获取作业提交列表
function getAssignmentSubmissions(assignmentId) {
    let xhr = new XMLHttpRequest()
    xhr.open("GET", "/admin/assignments/" + assignmentId + "/submissions", true)
    handleAjaxRequest(xhr,
        response=>{
            const submissionList = document.getElementById('submissionList');
            if (response.success && response.submissions && response.submissions.length > 0) {
                let submissionsHtml = '';
                response.submissions.forEach(submission => {
                    submissionsHtml += `
                        <tr>
                            <td>${submission.studentName || '未知学生'}</td>
                            <td>${submission.submitTime || ''}</td>
                            <td><span class="badge ${submission.status === 0 ? 'bg-warning' : 'bg-success'}">
                                ${submission.status === 0 ? '待批改' : '已批改'}
                            </span></td>
                            <td>${submission.score !== null ? submission.score : '-'}</td>
                            <td>${submission.comment || '-'}</td>
                            <td>
                                <button type="button" class="btn btn-sm btn-info" onclick="gradeSubmission(${submission.id})">
                                    <i class="fas fa-edit"></i> ${submission.status === 0 ? '批改' : '修改'}
                                </button>
                            </td>
                        </tr>
                    `;
                });
                submissionList.innerHTML = submissionsHtml;
            } else {
                submissionList.innerHTML = `<tr><td colspan="6" class="text-center">暂无提交记录</td></tr>`;
            }
        },error=>{
            const submissionList = document.getElementById('submissionList');
            submissionList.innerHTML = `<tr><td colspan="6" class="text-center">获取提交列表失败</td></tr>`;
        })
    xhr.send();
}

// 批改作业功能
function gradeSubmission(submissionId) {
    // 设置要批改的提交ID
    document.getElementById('submissionId').value = submissionId;
    
    // 清空之前的数据
    document.getElementById('score').value = '';
    document.getElementById('comment').value = '';
    
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('gradeSubmissionModal'));
    modal.show();
}

// 保存评分
document.getElementById('saveGradeBtn').addEventListener('click', function() {
    const submissionId = document.getElementById('submissionId').value;
    const score = document.getElementById('score').value;
    const comment = document.getElementById('comment').value;
    
    if (!score) {
        alert('请输入得分');
        return;
    }
    
    const xhr = new XMLHttpRequest();
    xhr.open('POST', '/admin/assignments/submissions/' + submissionId + '/grade', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    
    // 显示提交中提示
    const saveBtn = document.getElementById('saveGradeBtn');
    const originalBtnText = saveBtn.innerHTML;
    saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>提交中...';
    saveBtn.disabled = true;
    
    handleAjaxRequest(xhr,
        response => {
            // 恢复按钮状态
            saveBtn.innerHTML = originalBtnText;
            saveBtn.disabled = false;
            
            if (response.success) {
                alert('批改成功!');
                
                // 关闭模态框
                const modalElement = document.getElementById('gradeSubmissionModal');
                const modal = bootstrap.Modal.getInstance(modalElement);
                if (modal) {
                    modal.hide();
                }
                
                // 更新作业提交列表中的数据
                updateSubmissionInList(submissionId, response.submission);
            } else {
                alert('批改失败: ' + (response.error || '未知错误'));
            }
        },
        error => {
            // 恢复按钮状态
            saveBtn.innerHTML = originalBtnText;
            saveBtn.disabled = false;
            alert('批改失败: ' + error);
        }
    );
    
    // 发送数据
    const params = 'score=' + encodeURIComponent(score) + '&comment=' + encodeURIComponent(comment);
    xhr.send(params);
});

// 更新提交列表中的数据
function updateSubmissionInList(submissionId, submissionData) {
    // 查找对应行并更新数据
    const rows = document.querySelectorAll('#submissionList tr');
    for (let i = 0; i < rows.length; i++) {
        const row = rows[i];
        const button = row.querySelector('button');
        if (button && button.getAttribute('onclick').includes(submissionId)) {
            // 更新状态为"已批改"
            const statusCell = row.cells[2];
            statusCell.innerHTML = '<span class="badge bg-success">已批改</span>';
            
            // 更新得分
            row.cells[3].textContent = submissionData.score !== null ? submissionData.score : '-';
            
            // 更新评语
            row.cells[4].textContent = submissionData.comment || '-';
            
            // 更新按钮文本为"修改"
            button.innerHTML = '<i class="fas fa-edit"></i> 修改';
            break;
        }
    }
}

//删除回复
function delReply(replyId, buttonElement) {
    if (window.confirm('确认删除该帖子?')) {
        let xhr = new XMLHttpRequest();
        xhr.open("DELETE", "/admin/replies/" + replyId, true);
        handleAjaxRequest(xhr,
            response => {
                alert('删除成功!');
                //隐藏当前行即可
                const row = buttonElement.closest('tr');
                row.style.display = 'none';
            }, error => {
                alert('您的权限不足~')
            });
        xhr.send()
    }
}

// 发布作业或考试
document.getElementById('saveAssignmentBtn').addEventListener('click', function() {
    const form = document.getElementById('addAssignmentForm');
    // 验证必填字段
    const title = document.getElementById('assignmentSubTitle').value;
    if (!title) {
        console.error('标题输入框未找到，可能ID不匹配或页面未完全加载');
        alert('系统错误：无法找到标题输入框，请刷新页面重试');
        return;
    }

    // 检查标题是否为空或只包含空格
    if (!title || title.trim().length === 0) {
        alert('请输入标题');
        return;
    }

    // 检查标题是否只包含空格
    if (title.match(/^\s*$/)) {
        alert('标题不能只包含空格');
        return;
    }

    // 获取专业
    let majorId=document.getElementById('assignmentMajorSelect').value;
    if (!majorId) {
        alert('请选择专业');
        return;
    }
    // 获取描述
    let description=document.getElementById('assignmentSubDescription').value;
    if (!description) {
        alert('请输入作业/考试描述');
        return;
    }

    // 获取截止时间
    const deadline = document.getElementById('assignmentSubDeadline').value;
    if (!deadline) {
        alert('请选择截止时间');
        return;

    }

    // 获取附件（如果存在）
    const fileElement = document.getElementById('assignmentFile');
    let file = null;
    if (fileElement && fileElement.files && fileElement.files[0]) {
        file = fileElement.files[0];
    }

    // 创建XMLHttpRequest对象
    const xhr = new XMLHttpRequest();
    xhr.open('POST', '/admin/assignments', true);

    // 显示提交中提示
    const saveBtn = document.getElementById('saveAssignmentBtn');
    const originalBtnText = saveBtn.innerHTML;
    saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>提交中...';
    saveBtn.disabled = true;

    // 创建FormData对象并添加数据
    const formData = new FormData();
    formData.append('title', title);
    formData.append('majorId', majorId);
    formData.append('description', description);
    formData.append('deadline', deadline);

    // 如果有附件，添加到FormData中
    if (file) {
        formData.append('file', file);
    }

    handleAjaxRequest(xhr,
        response => {
            // 复按钮状态
            saveBtn.innerHTML = originalBtnText;
            saveBtn.disabled = false;

            alert('发布成功!');
            // 关闭模态框
            const modalElement = document.getElementById('addassignmentModal');
            const modal = bootstrap.Modal.getInstance(modalElement);
            if (modal) {
                modal.hide();
            }

            // 重置表单
            form.reset();

            // 刷新页面以显示新添加的作业
            location.reload();
        },
        error => {
            // 复 button status
            saveBtn.innerHTML = originalBtnText;
            saveBtn.disabled = false;

            alert('发布失败: ' + error);
        }
    );

    xhr.send(formData);
});